package org.example.proxy;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import org.example.Model.RequestData;
import org.example.Model.ResponseData;
import org.example.serialize.JdkSerializer;
import org.example.serialize.Serializer;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class UserServiceDynamicProxy implements InvocationHandler {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 指定序列化器
        Serializer serializer = new JdkSerializer();
        // 准备发送数据
        RequestData requestData = new RequestData().builder()
                .serviceName(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .parameterTypes(method.getParameterTypes())
                .args(args)
                .build();
        // 序列化请求数据
        try {
            byte[] bytes = serializer.serialize(requestData);
            HttpResponse httpResponse = HttpRequest.post("http://localhost:8080")
                    .body(bytes)
                    .execute();
            ResponseData responseData = serializer.deserialize(httpResponse.bodyBytes(), ResponseData.class);
            return responseData.getData();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
